package models

import (
	"fmt"
	"strconv"
	"time"
	"xorm.io/builder"
)

type Terminal struct {
	Id              int64     `form:"terminal_id" xorm:"not null pk autoincr comment('自增主键') INT(11)"`
	InstitutionCode string    `xorm:"comment('运管统一编号') index CHAR(16)"`
	SchoolId        int       `form:"school_id" xorm:"not null comment('驾校id，外键关联dts_school表中的id') index INT(11)"`
	TerminalGroupId int       `xorm:"not null comment('计时终端设备id，外键关联dts_terminal_group表中的id') index INT(11)"`
	Brand           string    `form:"brand" xorm:"default '' comment('生产厂家') VARCHAR(128)"`
	TerminalSerial  string    `form:"terminal_serial" xorm:"default '' comment('终端型号') VARCHAR(128)"`
	SerialCode      string    `form:"serial_code" xorm:"not null comment('终端出厂序列号') VARCHAR(128)"`
	Type            string    `form:"type" xorm:"default '1' comment('终端类型，1：车载，2：课堂教学，3：模拟训练，4：其他') ENUM('1','2','3','4')"`
	Imei            string    `form:"imei" xorm:"default '' comment('终端国际移动设备标识符') index VARCHAR(128)"`
	Mac             string    `form:"mac" xorm:"default '' comment('终端mac地址') VARCHAR(128)"`
	Certificate     string    `xorm:"not null default '' comment('终端证书') VARCHAR(10000)"`
	CertificateKey  string    `xorm:"not null default '' comment('终端证书密码') CHAR(12)"`
	InstallDate     time.Time `xorm:"comment('安装日期 YYYYMMDD') DATE"`
	Status          string    `xorm:"default '1' comment('终端当前工作状态，0：关机，1：待机，2：教学，3：跑点，4：禁用') ENUM('0','1','2','3','4')"`
	ApprovalStatus  string    `xorm:"default '1' comment('终端设备提交运管审核状态，0:待审核，1:通过审核，2:未通过审核') ENUM('0','1','2')"`
	RecordStatus    string    `xorm:"not null default '0' comment('备案状态 0:未备案 1:已备案') ENUM('0','1')"`
	Flameout        string    `form:"flameout" xorm:"default '0' comment('0 : 不熄火；1 : 熄火') ENUM('0','1')"`
	Remark          string    `xorm:"VARCHAR(255)"`
	Isused          string    `xorm:"default '1' comment('1 正在使用  0已删除') ENUM('0','1')"`
	Hisimei         string    `xorm:"VARCHAR(128)"`
}

// 页面显示的结构体列表项
type TerminalInfo struct {
	Id              int    `json:"id"`
	InstitutionCode string `json:"institution_code"`
	SchoolId        string `json:"school_id"`
	SchoolName      string `json:"school_name"`
	Type            string `json:"type"`
	Brand           string `json:"brand"`
	TerminalSerial  string `json:"terminal_serial"`
	Imei            string `json:"imei"`
	PlateNumber     string `json:"plate_number"`
	InstallDate     string `json:"install_date"`
	Sim             string `json:"sim"`
	Status          string `json:"status"`
	SerialCode      string `json:"serial_code"`
	ApprovalStatus  string `json:"approval_status"`
	RecordStatus    string `json:"record_status"`
	Flameout        string `json:"flameout"`
	Reged           string `json:"reged"`
}

func (c *Terminal) GetTerminalByFilter(filter builder.Cond, pageSize, offset int) (count int64, list []*TerminalInfo, err error) {
	err = engine.Table("dts_terminal").Alias("t").
		Select("t.id,t.institution_code,s.name_short as school_name,t.school_id,t.type,t.brand,t.terminal_serial,t.serial_code,t.imei,t.install_date,t.status,t.approval_status,t.record_status,t.flameout,c.plate_number,tc.sim,tc.reged").
		Join("LEFT", []string{"dts_terminal_car", "tc"}, "tc.terminal_id=t.id").
		Join("LEFT", []string{"dts_car", "c"}, "c.id=tc.car_id").
		Join("LEFT", []string{"dts_school", "s"}, "s.id=t.school_id").
		And(filter).Desc("t.id").Limit(pageSize, offset).Find(&list)
	count, err = engine.Table("dts_terminal").Alias("t").
		Join("LEFT", []string{"dts_terminal_car", "tc"}, "tc.terminal_id=t.id").
		Join("LEFT", []string{"dts_car", "c"}, "c.id=tc.car_id").
		Join("LEFT", []string{"dts_school", "s"}, "s.id=t.school_id").
		And(filter).Count()
	return
}

func (c *Terminal) GetOneTerminalById(id int64) (has bool, list Terminal, err error) {
	has, err = engine.Table("dts_terminal").
		Where("id = ?", id).
		Get(&list)
	return has, list, err
}

func (c *Terminal) GetTerminalByImei(imei string) (list *Terminal, err error) {
	list = new(Terminal)
	_, err = engine.Table("dts_terminal").
		Where("imei = ?", imei).
		Get(list)
	return list, err
}

// 添加终端信息
func (c *Terminal) Save() bool {
	var (
		err error
	)
	c.Isused = "1"
	c.Remark = ""
	c.Hisimei = ""
	_, err = engine.Table("dts_terminal").Insert(c)
	if err != nil {
		return false
	}
	return true
}

// 根据id获取终端信息
func (c *Terminal) GetTerminalById(Id string) (list *Terminal) {
	list = new(Terminal)
	if terminalid, err := strconv.ParseInt(Id, 10, 64); err != nil {
		fmt.Println(err.Error())
		return
	} else {
		if _, err := engine.Table("dts_terminal").Select("*").Where("id=? and isused=?", terminalid, "1").Get(list); err != nil {
		}
	}
	return
}

func (c *Terminal) Update(field ...string) bool {
	var (
		err error
	)
	_, err = engine.Table("dts_terminal").Id(c.Id).Cols(field...).Update(c)
	if err != nil {
		return false
	}
	return true
}
